<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索and添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名"
            clearable
            @clear="getUserList"
            v-model="queryInfo.query"
            @keyup.enter.native="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="id" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色部分 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogVisibleClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close='setRoleDialogClosed'
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱的自定义规则
    let checkEmail = (rule, value, callback) => {
      const regEmail =
        /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
      //验证通过的合法邮箱
      if (regEmail.test(value)) return callback();
      //未通过的不合法邮箱
      callback(new Error('邮箱不合法！'));
    };
    //验证手机的自定义规则
    let checkPhone = (rule, value, callback) => {
      let regPhone =
        /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/;
      //验证通过的合法手机号
      if (regPhone.test(value)) return callback();
      //未通过的不合法邮箱
      callback(new Error('手机号不合法！'));
    };
    return {
      //存储请求用户列表的参数数据
      queryInfo: {
        query: '',
        //当前显示的页
        pagenum: 1,
        //当前页显示数据的条数
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      //控制显示隐藏添加用户对话框
      dialogVisible: false,
      //添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //添加用户的表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 1,
            max: 6,
            message: '用户名长度在 1 到 6 位！',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '密码长度在 6 到 12 位！',
            trigger: 'blur',
          },
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          {
            validator: checkPhone,
            trigger: 'blur',
          },
        ],
      },
      //控制是否展示修改用户对话框
      editDialogVisible: false,
      //保存查询成功的数据
      editForm: {},
      //修改用户的表单验证规则对象
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          {
            validator: checkPhone,
            trigger: 'blur',
          },
        ],
      },
      //管理分配角色对话框
      setRoleDialogVisible: false,
      //存储分配角色者本身的角色
      userInfo: {},
      //角色权限列表数据
      rolesList: [],
      //保存角色权限保存的
      selectedRoleId: '',
    };
  },
  created() {
    this.getUserList(); //生命周期函数在页面生成时就会自动执行(代表打开页面直接调用方法请求接口)
  },
  methods: {
    async getUserList() {
      //get方式请求用户列表数据
      const { data: response } = await this.$http.get('users', {
        params: this.queryInfo,
      });
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.userlist = response.data.users;
      this.total = response.data.total;
    },
    //监听选择展示条数控件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize; //当前选择要展示的值赋过去
      this.getUserList(); //拿着赋过去最新的值发送新的请求
    }, //监听页码值发生变化的时间
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage; //当前选择要展示的页
      this.getUserList(); //发送新的请求
    },
    //监听switch开关状态的改变
    async userStateChanged(userInfo) {
      const { data: response } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (response.meta.status !== 200) {
        //请求失败则设置回原先状态
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      }
      this.$message({
        message: '成功更新用户状态',
        type: 'success',
        center: true,
      });
    },
    //监听关闭添加用户对话框的关闭事件
    dialogVisibleClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮添加新用户
    addUser() {
      //调用表单预校验满足不满足要求则不执行添加
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: response } = await this.$http.post('users', this.addForm);
        if (response.meta.status !== 201)
          return this.$message({
            message: response.meta.msg,
            type: 'error',
            center: true,
          });
        //提示添加成功并关闭表单重新请求用户列表
        this.$message({
          message: '添加用户成功！',
          type: 'success',
          center: true,
        });
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    //展示编辑用户对话框
    async showEditDialog(id) {
      const { data: response } = await this.$http.get('users/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.editForm = response.data;
      this.editDialogVisible = true;
    },
    //监听修改用户对话框的关闭事件清空修改项
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户信息并提交校验
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: response } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (response.meta.status !== 200)
          return this.$message({
            message: response.meta.msg,
            type: 'error',
            center: true,
          });
        this.editDialogVisible = false;
        this.getUserList();
        this.$message({
          message: '修改成功',
          type: 'success',
          center: true,
        });
      });
    },
    //删除用户
    async removeUser(id) {
      const confirmResult = await this.$confirm('确认永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      const { data: response } = await this.$http.delete('users/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.$message({
        message: response.meta.msg,
        type: 'success',
        center: true,
      });
      this.getUserList();
    },
    //分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo;
      //在展示对话框之前获取展示所有角色列表
      const { data: response } = await this.$http.get('roles');
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.rolesList = response.data;

      this.setRoleDialogVisible = true;
    },
    //设置为确定选定的角色
    async saveRoleInfo() {
      if (this.selectedRoleId === '')
        return this.$message({
          message: '请选择一个角色',
          type: 'error',
          center: true,
        });
      const {data:response} = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId,
      });
      if(response.meta.status !== 200) return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
        this.setRoleDialogVisible = false
        this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.getUserList()
    },
    //监听处理关闭选择角色对话框的事件
    setRoleDialogClosed(){
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  },
};
</script>

<style scoped>
</style>